const app = getApp();
import {
  post
} from '../../utils/request';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    info: null,
    loginInfo: null,

    remark: '', // 商品备注
    amount: '0.00', // 支付总额
    num: 0, // 商品总数
  },

  // 立即支付
  onPay() {
    let that = this;
    wx.showLoading({
      title: '正在支付',
    });
    post("/order/pay", {
      ...that.data.info.detail[0],
      remark: that.data.remark
    }).then(res => {
      wx.hideLoading();
      if (res.code === 0) {
        wx.requestPayment({
          timeStamp: res.data.timeStamp,
          nonceStr: res.data.nonceStr,
          package: res.data.package,
          signType: res.data.signType,
          paySign: res.data.paySign,
          success() {
            wx.reLaunch({
              url: '/pages/order/my',
            });
          },
          fail() {
            wx.showModal({
              title: '温馨提示',
              content: '你已取消支付，需要重新支付吗？',
              confirmText: '立即支付',
              complete: (result) => {
                if (result.cancel) {
                  wx.reLaunch({
                    url: '/pages/order/my',
                  });
                }
                if (result.confirm) {
                  that.payByNo(res.data.orderNo);
                }
              }
            })
          }
        })
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'error'
        });
      }
    });
  },

  // 根据订单号支付
  payByNo(orderNo) {
    let that = this;
    wx.showLoading({
      title: '正在支付',
      mask: true,
    });
    post(`/order/pay-by-no/${orderNo}`)
      .then(res => {
        wx.hideLoading();
        if (res.code === 0) {
          wx.requestPayment({
            timeStamp: res.data.timeStamp,
            nonceStr: res.data.nonceStr,
            package: res.data.package,
            signType: res.data.signType,
            paySign: res.data.paySign,
            success() {
              wx.reLaunch({
                url: '/pages/order/my',
              });
            },
            fail() {
              wx.showModal({
                title: '温馨提示',
                content: '你已取消支付，需要重新支付吗？',
                confirmText: '立即支付',
                complete: (result) => {
                  if (result.cancel) {
                    wx.reLaunch({
                      url: '/pages/order/my',
                    });
                  }
                  if (result.confirm) {
                    that.payByNo(res.data.orderNo);
                  }
                }
              })
            }
          })
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'error'
          });
        }
      })
  },

  // 监听备注输入框
  onRemarkChg(e) {
    let {
      value
    } = e.detail;
    this.setData({
      remark: value
    });
  },

  // 减数量
  onReduce(e) {
    let {
      info
    } = this.data;
    let {
      detail
    } = info;
    let {
      idx
    } = e.currentTarget.dataset;

    let detailItem = detail[idx];
    if (detailItem.num > 1) {
      detailItem.num -= 1;
      detail[idx] = detailItem;
      info.detail = detail;
      this.setData({
        info
      });
      this.setAmount();
    }
  },

  // 加数量
  onPlus(e) {
    let {
      info
    } = this.data;
    let {
      detail,
      list
    } = info;
    let {
      idx
    } = e.currentTarget.dataset;

    let detailItem = detail[idx];
    let listItem = list[idx];
    if (detailItem.num < listItem.spec.stock) {
      detailItem.num += 1;
      detail[idx] = detailItem;
      info.detail = detail;
      this.setData({
        info
      });
      this.setAmount();
    }
  },

  // 支付金额
  setAmount() {
    if (!this.data.info) {
      return;
    }
    let amount = 0;
    let num = 0;
    this.data.info.list.forEach((d, i) => {
      if(this.data.info.detail[i].type===0) { // 商品
        amount += d.spec.sellPrice * this.data.info.detail[i].num;
      }
      if(this.data.info.detail[i].type===1) { // 服务
        amount += d.card.sellPrice * this.data.info.detail[i].num;
      }
      if(this.data.info.detail[i].type===2) { // 套餐
        amount += d.sellPrice * this.data.info.detail[i].num;
      }
      num += this.data.info.detail[i].num;
    });
    this.setData({
      amount: (amount / 100).toFixed(2),
      num
    });
  },

  // 获取订单信息
  getInfo(id) {
    app.checkLogin(true, () => {
      wx.showLoading({
        title: '正在加载',
        mask: true
      });
      post(`/order/pre-info/${id}`)
        .then(res => {
          wx.hideLoading();
          if (res.code === 0) {
            this.setData({
              info: res.data
            });
            this.setAmount();
          } else {
            wx.showModal({
              title: '提示',
              content: res.msg,
              showCancel: false,
              success(res) {
                if (res.confirm) {
                  wx.navigateBack();
                }
              }
            })
          }
        });
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    wx.setBackgroundColor({
      backgroundColor: "#f6f6f6"
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    let options = app.getPageOptions();
    if (options.id) {
      this.getInfo(options.id);
    }

    this.setData({
      loginInfo: app.getLoginInfo()
    });

  },

});